﻿//Copyright 2011 - Jonathan Allen

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using Granite.Collections;

namespace Granite.Eventing
{
	/// <summary>
	/// This is used to attach weak event handlers to the indicated source.
	/// </summary>
	/// <remarks>
	/// If a class encapsulates this then it should also implement INotifyItemPropertyChangedWeak.
	/// </remarks>
	public sealed class ItemPropertyChangedEventManager : EventManager<RelayedEventArgs<PropertyChangedEventArgs>>
	{
		readonly INotifyItemPropertyChanged m_Source;

		/// <summary>
		/// Creates a new CollectionChangedEventManager.
		/// </summary>
		/// <param name="source"></param>
		public ItemPropertyChangedEventManager(INotifyItemPropertyChanged source)
		{
			if (source == null)
				throw new ArgumentNullException("source", "source is null.");
			Contract.EndContractBlock();

			m_Source = source;
		}

		/// <summary>
		/// The implementation of this event must attach the event source to the EventFired method.
		/// </summary>
		protected override void AttachToEvent()
		{
			m_Source.ItemPropertyChanged += EventFired;
		}

		/// <summary>
		/// The implementation of this event must deattach the event source to the EventFired method.
		/// </summary>
		protected override void DetachFromEvent()
		{
			m_Source.ItemPropertyChanged -= EventFired;
		}

		[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic"), SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
		[ContractInvariantMethod]
		void ObjectInvariant()
		{
			Contract.Invariant(m_Source != null);
		}

	}
}
